import subprocess
import threading
import os
import re
from queue import Queue
from tkinter import messagebox
from ui import NetConfigUI

class NetConfigApp:
    def __init__(self, root):
        self.root = root
        self.ui = NetConfigUI(root, self)
        
        self.is_running = False
        self.process = None
        self.output_queue = Queue()
        
        # 初始化
        self.check_interfaces()
        self.root.after(100, self.update_output)
        self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
    
    def update_output(self):
        """定时更新输出"""
        try:
            while not self.output_queue.empty():
                line = self.output_queue.get_nowait()
                self.ui.append_output(line)
        except:
            pass
        self.root.after(100, self.update_output)
    
    def check_interfaces(self):
        """检测网口"""
        try:
            result = subprocess.run(
                ['ip', 'link', 'show'],
                capture_output=True,
                text=True,
                check=True
            )
            
            interfaces = re.findall(r'^\d+: (enx?[a-z0-9]*|eth[a-z0-9]*):', result.stdout, re.MULTILINE)
            
            if interfaces:
                self.ui.set_interfaces(interfaces)
                
                # 优先选择enx接口
                enx_ifaces = [i for i in interfaces if i.startswith('enx')]
                if enx_ifaces:
                    self.ui.target_interface.set(enx_ifaces[0])
                
                self.ui.update_status(f"✓ 检测到 {len(interfaces)} 个网口")
                self.output_queue.put(f"✓ 发现网口: {', '.join(interfaces)}\n")
            else:
                self.ui.set_interfaces([])
                
                all_interfaces = re.findall(r'^\d+: (\w+):', result.stdout, re.MULTILINE)
                filtered_out = [i for i in all_interfaces if not i.startswith(('lo', 'wlan', 'virbr', 'docker', 'veth'))]
                
                self.ui.update_status("⚠️ 无 en/eth 网口", '#FF9800')
                self.output_queue.put("⚠️ 警告: 未找到 en* 或 eth* 网口\n")
                if filtered_out:
                    self.output_queue.put(f"   已过滤: {', '.join(filtered_out)}\n")
                self.output_queue.put("   请检查硬件连接\n")
                
        except Exception as e:
            self.ui.update_status(f"✗ 检测失败: {e}", '#f44336')
            self.output_queue.put(f"✗ 错误: {e}\n")
    
    def select_script(self):
        """选择脚本文件 - 现在由UI类直接处理"""
        # 这个方法现在为空，因为功能已经移到UI类中
        pass
    
    def start_config(self):
        """开始配置"""
        config = self.ui.get_config_values()
        script = config['script_path']
        interface = config['interface']
        
        if not os.path.exists(script):
            messagebox.showerror("错误", f"脚本不存在: {script}")
            return
        
        if not interface:
            messagebox.showwarning("警告", "请选择目标网口")
            return
        
        # 检查脚本权限
        if not os.access(script, os.X_OK):
            resp = messagebox.askyesno("权限不足", "脚本没有执行权限，是否自动添加？")
            if resp:
                try:
                    os.chmod(script, 0o755)
                    self.output_queue.put("✓ 已添加执行权限\n")
                except Exception as e:
                    messagebox.showerror("错误", f"添加权限失败: {e}")
                    return
            else:
                return
        
        # 构建命令
        cmd = ['sudo', script]
        if config['auto_mode']:
            cmd.append('-y')
        cmd.extend(['-i', interface])
        
        self.is_running = True
        self.ui.set_buttons_state(True)
        self.ui.update_status("⏳ 配置中...", '#2196F3')
        
        thread = threading.Thread(target=self.run_script_thread, args=(cmd,))
        thread.daemon = True
        thread.start()
    
    def run_script_thread(self, cmd):
        """脚本执行线程"""
        try:
            self.output_queue.put(f"\n{'='*50}\n")
            self.output_queue.put(f"执行: {' '.join(cmd)}\n")
            self.output_queue.put(f"{'='*50}\n")
            
            self.process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                text=True,
                bufsize=1
            )
            
            for line in iter(self.process.stdout.readline, ''):
                if line:
                    clean_line = re.sub(r'\x1b\[[0-9;]*m', '', line)
                    self.output_queue.put(clean_line)
            
            return_code = self.process.wait()
            
            if return_code == 0:
                self.output_queue.put("\n✅ 配置流程完成\n")
                self.ui.update_status("✓ 配置完成")
            else:
                self.output_queue.put(f"\n❌ 脚本退出码: {return_code}\n")
                self.ui.update_status("✗ 配置失败", '#f44336')
                
        except Exception as e:
            self.output_queue.put(f"\n错误: {e}\n")
            self.ui.update_status("✗ 执行错误", '#f44336')
        finally:
            self.is_running = False
            self.process = None
            self.ui.set_buttons_state(False)
    
    def restart_network_interface(self):
        """重启网络接口"""
        interface = self.ui.target_interface.get()
        
        if not interface:
            messagebox.showwarning("警告", "请先选择网口")
            return
        
        self.output_queue.put("\n" + "="*50 + "\n")
        self.output_queue.put(f"重启网络接口: {interface}\n")
        self.output_queue.put("="*50 + "\n")
        
        self.ui.set_buttons_state(True)
        self.ui.update_status("⏳ 重启中...", '#2196F3')
        
        thread = threading.Thread(target=self.restart_thread, args=(interface,))
        thread.daemon = True
        thread.start()
    
    def restart_thread(self, interface):
        """网络重启线程"""
        try:
            # 停止接口
            self.output_queue.put("1. 停止接口...\n")
            down_result = subprocess.run(
                ['sudo', 'ifdown', interface],
                capture_output=True,
                text=True
            )
            if down_result.returncode == 0:
                self.output_queue.put("   ✅ 接口已停止\n")
            else:
                self.output_queue.put(f"   ⚠️  警告: {down_result.stderr}\n")
            
            # 等待1秒
            self.output_queue.put("   等待1秒...\n")
            import time
            time.sleep(1)
            
            # 启动接口
            self.output_queue.put("2. 启动接口...\n")
            up_result = subprocess.run(
                ['sudo', 'ifup', interface],
                capture_output=True,
                text=True
            )
            if up_result.returncode == 0:
                self.output_queue.put("   ✅ 接口已启动\n")
            else:
                self.output_queue.put(f"   ❌ 启动失败: {up_result.stderr}\n")
            
            # 验证IP配置
            self.output_queue.put("3. 验证IP配置...\n")
            ip_result = subprocess.run(
                ['ip', 'addr', 'show', interface],
                capture_output=True,
                text=True
            )
            
            if "192.168.123.222" in ip_result.stdout:
                self.output_queue.put("   ✅ IP配置正确: 192.168.123.222\n")
            else:
                self.output_queue.put("   ❌ IP配置异常，请重新配置网络\n")
                self.output_queue.put("   当前状态:\n")
                for line in ip_result.stdout.split('\n'):
                    if 'inet' in line:
                        self.output_queue.put(f"      {line.strip()}\n")
            
            # 检查链路状态
            self.output_queue.put("4. 检查链路状态...\n")
            link_result = subprocess.run(
                ['ip', 'link', 'show', interface],
                capture_output=True,
                text=True
            )
            
            if "UP" in link_result.stdout and "LOWER_UP" in link_result.stdout:
                self.output_queue.put("   ✅ 链路正常\n")
            else:
                self.output_queue.put("   ⚠️  链路异常，请检查网线\n")
            
            self.output_queue.put("\n重启完成！\n")
            self.ui.update_status("✓ 重启完成")
            
        except Exception as e:
            self.output_queue.put(f"✗ 重启错误: {e}\n")
            self.ui.update_status("✗ 重启错误", '#f44336')
        finally:
            self.ui.set_buttons_state(False)
    
    def test_connection(self):
        """测试连接"""
        if not self.ui.target_interface.get():
            messagebox.showwarning("警告", "请先选择网口")
            return
        
        self.output_queue.put("\n--- 连接测试开始 ---\n")
        thread = threading.Thread(target=self.ping_test_thread)
        thread.daemon = True
        thread.start()
    
    def ping_test_thread(self):
        """Ping测试线程"""
        try:
            # 检查sudo权限
            self.output_queue.put("1. 检查sudo权限...\n")
            sudo_check = subprocess.run(['sudo', '-n', 'true'], capture_output=True, timeout=3)
            if sudo_check.returncode != 0:
                self.output_queue.put("   ❌ sudo需要密码\n")
                self.output_queue.put("   💡 配置免密码: sudo visudo\n")
                return
            self.output_queue.put("   ✅ sudo正常\n\n")
            
            # 执行ping测试
            self.output_queue.put("2. Ping测试...\n")
            ping_result = subprocess.run(
                ['sudo', 'ping', '-c', '3', '-W', '2', '192.168.123.161'],
                capture_output=True,
                text=True,
                timeout=10
            )
            
            if ping_result.stdout:
                for line in ping_result.stdout.split('\n'):
                    if line:
                        self.output_queue.put(f"   {line}\n")
            
            if ping_result.returncode == 0:
                self.output_queue.put("\n   ✅ 连接成功\n")
            else:
                self.output_queue.put("\n   ❌ 连接失败\n")
                
        except Exception as e:
            self.output_queue.put(f"✗ 错误: {e}\n")
    
    def on_closing(self):
        """关闭程序"""
        try:
            if self.is_running and self.process and self.process.poll() is None:
                subprocess.run(['sudo', 'kill', '-9', str(self.process.pid)], 
                             capture_output=True, check=False)
                self.process.wait(timeout=2)
            
            self.root.quit()
            self.root.destroy()
            os._exit(0)
            
        except Exception as e:
            print(f"关闭错误: {e}")
            self.root.quit()
            self.root.destroy()
            os._exit(0)

def main():
    import tkinter as tk
    root = tk.Tk()
    app = NetConfigApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()